<!--
 * @Author: 陈俊升 761723995@qq.com
 * @Date: 2023-11-20 13:50:33
 * @LastEditors: 陈俊升 761723995@qq.com
 * @LastEditTime: 2024-01-02 15:53:30
 * @FilePath: /hr_new_vue3/src/components/ContractTemplateModal/index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!-- 选择合同附件模板弹出框 -->
<template>
  <a-modal
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    width="80%"
    :mask-closable="false"
    title-align="center"
    :body-style="{
      height: '500px'
    }"
  >
    <template #title> 选择模板 </template>

    <div class="layout-demo">
      <a-layout>
        <a-layout>
          <a-layout-sider class="sider">
            <a-input-search
              allow-clear
              class="search"
              placeholder="输入分类名称"
              v-model="searchVal"
              @change="changeVal"
            />
            <a-tree
              show-line
              :data="treeData"
              :field-names="{
                key: 'id',
                title: 'name'
              }"
              v-model:selected-keys="selectedKey"
              v-model:expanded-keys="expandKey"
              @select="selectTree"
            >
              <template #switcher-icon="node, { isLeaf }">
                <IconDown v-if="!isLeaf" />
                <IconStar v-if="isLeaf" />
              </template>
              <!-- <template #title="nodeData">
                <template
                  v-if="((index = getMatchIndex(nodeData.name)), index < 0)"
                  >{{ nodeData.name }}</template
                >
                <span v-else>
                  {{ nodeData.name?.substr(0, index) }}
                  <span style="color: var(--color-primary-light-4)">
                    {{ nodeData.name?.substr(index, searchVal.length) }} </span
                  >{{ nodeData.name?.substr(index + searchVal.length) }}
                </span>
              </template> -->
            </a-tree>
          </a-layout-sider>
          <a-layout-content class="ml-5">
            <TableTurn :tableData="getTableData" ref="tableRef" :args="args">
              <a-table-column :width="80">
                <template #title> 序号 </template>
                <template #cell="{ rowIndex }">
                  {{ rowIndex + 1 }}
                </template>
              </a-table-column>
              <a-table-column
                :width="200"
                data-index="name"
                title="合同模板名称"
              >
              </a-table-column>
              <!-- <a-table-column
                :width="200"
                data-index=""
                title="操作"
                fixed="right"
              >
                <template #cell="{ record }">
                  <a-tooltip content="复制">
                    <a-popconfirm
                      content="是否确认复制该条数据?"
                      @ok="copy(record)"
                    >
                      <icon-copy
                        size="18"
                        style="
                          padding-bottom: 3px;
                          padding-right: 10px;
                          color: #5085ff;
                          cursor: pointer;
                        "
                      />
                    </a-popconfirm>
                  </a-tooltip>
                  <a-tooltip content="编辑">
                    <IconFont
                      type="icon-edit"
                      :size="26"
                      :style="{
                        marginRight: '10px',
                        cursor: 'pointer'
                      }"
                      @click="goEdit(record)"
                    />
                  </a-tooltip>
                  <a-tooltip content="删除" position="left">
                    <a-popconfirm
                      content="是否确认删除该条数据?"
                      @ok="del(record.id)"
                    >
                      <icon-font
                        type="icon-delete"
                        :size="26"
                        :style="{
                          cursor: 'pointer',
                          marginRight: '10px'
                        }"
                      />
                    </a-popconfirm>
                  </a-tooltip>
                </template>
              </a-table-column> -->
            </TableTurn>
          </a-layout-content>
        </a-layout>
      </a-layout>
    </div>
  </a-modal>
</template>
<script setup lang="ts">
import { flatTree } from '@/utils/utils';
import {
  GetContractGroup,
  GetContractTemplateList
} from '@/apis/management/contract/baseSetting';

const props = defineProps<{
  visible: boolean;
}>();

const emits = defineEmits(['update:visible', 'contractAttachmentTemplateEmit']);

let searchVal = ref(''); // 搜索框
let groupList = ref([]); // 储存合同分类数据
let flatData = ref<any>([]); // 储存扁平化的数据
let tableRef = ref();
const selectedListData = computed(() => tableRef.value.selectedListData);

const args = reactive({
  rowSelection: {
    type: 'checkbox'
  }
});

const getData = async () => {
  try {
    const [groupListRes] = await Promise.all([
      GetContractGroup({
        name: searchVal.value,
        pageNumber: 0,
        pageSize: -1
      })
    ]);
    groupList.value = dealTreeData(groupListRes.content);
    flatData.value = flatTree(groupListRes.content);

    // // 默认展开所有行
    flatData.value.forEach((item: any) => {
      expandKey.value.push(item.id);
    });
    currSelectedData.value = flatData.value[1].id;
    selectedKey.value = [flatData.value[1].id];

    tableRef.value.loadData();
  } catch (error: unknown) {
    console.log(error);
  }
};

let expandKey: any = ref([]); // 储存当前搜索要展开的选项
let selectedKey = ref<number[]>([]); // 选中的值
const dealTreeData = (treeData) => {
  const data = treeData.map((item) => ({
    ...item,
    // id: item.children ? null : item.id,
    // 新增title字段
    title: item.name,
    // 新增叶子节点字段
    isLeaf: item.children ? false : true,
    selectable: item.children ? false : true,
    // 如果children为空数组，则置为null
    children:
      item.children && item.children.length ? dealTreeData(item.children) : null
  }));
  return data;
};

watch(
  () => props.visible,
  (newVal: boolean) => {
    if (newVal) getData();
  }
);

// 搜索值
const searchData = (keyword: string) => {
  const loop = (data: any) => {
    const result: any = [];
    data.forEach((item: any) => {
      if (item.name.toLowerCase().indexOf(keyword.toLowerCase()) > -1) {
        result.push({ ...item });
      } else if (item.children) {
        const filterData = loop(item.children);
        if (filterData.length) {
          result.push({
            ...item,
            children: filterData
          });
          expandKey.value.push(item.id);
        }
      }
    });
    return result;
  };

  return loop(groupList.value);
};

/* 储存实时的属性数据 */
const treeData = computed(() => {
  if (!searchVal.value) return groupList.value;
  return searchData(searchVal.value);
});

const getMatchIndex = (name: string): number => {
  if (!searchVal.value) return -1;
  return name.toLowerCase().indexOf(searchVal.value.toLowerCase()) as number;
};

let currSelectedData = ref();
// 点击导航栏跳往对应详情
const selectTree = (selectedKeys: Array<number>, data: any) => {
  selectedKey.value = selectedKeys;
  currSelectedData.value = data.node.id;
  tableRef.value.loadData();
  console.log(data);
};

const getTableData = async (pageData?: any) => {
  try {
    const res = await GetContractTemplateList({
      ...pageData,
      typeId: currSelectedData.value
    });
    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log(error);
  }
};

const handleOk = () => {
  emits('contractAttachmentTemplateEmit', selectedListData.value);
  emits('update:visible', false);
};

const handleCancel = () => {
  emits('update:visible', false);
};
</script>
<style scoped lang="less">
.layout-demo {
  height: 100%;

  .sider {
    height: 100%;
    overflow: auto;
  }
}
.arco-layout,
.arco-layout .arco-layout-has-sider {
  height: 100%;
}
</style>
